package com.hdaccp.hadoop.mr;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class MusicCountApp {
    public static class MusicMapper extends Mapper<LongWritable,Text,Text,LongWritable>
    {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
           //
            String line = value.toString() ;
            String songType = line.split("\t")[3] ;
            context.write(new Text(songType),new LongWritable(1));
            /**
             * slow 1
             * slow 1
             * quick 1
             * quick 1
             * quick 1
             * quick 1
             * quick 1
             */
        }
    }

    /**
     * slow [1,1]
     * quick [1,1,1,1,1]
     */
    public static class MusicReducer extends Reducer<Text,LongWritable,Text,LongWritable>
    {
        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            long sum = 0 ;
            for(LongWritable w :values){
                sum = sum + w.get() ;
            }
            context.write(key,new LongWritable(sum));
        }
    }

    public static void main(String[] args) throws  Exception{

        //创建Configuration
        Configuration configuration = new Configuration();

        //创建Job
        Job job = Job.getInstance(configuration, "musicwordcount");

        //设置job的处理类
        job.setJarByClass(MusicCountApp.class);

        //设置作业处理的输入路径
        FileInputFormat.setInputPaths(job, new Path(args[0]));

        //设置map相关参数
        job.setMapperClass(MusicMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        //设置reduce相关参数
        job.setReducerClass(MusicReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        Path outpath = new Path(args[1]) ;
        //
        FileSystem fileSystem = FileSystem.get(configuration) ;
        if(fileSystem.exists(outpath)){
            fileSystem.delete(outpath,true) ;
        }
        //设置作业处理的输出路径
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }

}
